package com.ma.process.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ma.auth.service.SysUserService;
import com.ma.model.process.Process;
import com.ma.model.process.ProcessRecord;
import com.ma.model.process.ProcessTemplate;
import com.ma.model.system.SysUser;
import com.ma.process.mapper.ProcessMapper;
import com.ma.process.service.OaProcessTemplateService;
import com.ma.process.service.ProcessRecordService;
import com.ma.process.service.ProcessService;
import com.ma.security.custom.LoginUserInfoHelper;
import com.ma.vo.process.ApprovalVo;
import com.ma.vo.process.ProcessFormVo;
import com.ma.vo.process.ProcessQueryVo;
import com.ma.vo.process.ProcessVo;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

@Service
public class ProcessServiceImpl extends ServiceImpl<ProcessMapper, Process> implements ProcessService {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private OaProcessTemplateService processTemplateService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ProcessRecordService processRecordService;
    @Autowired
    private HistoryService historyService;

    @Override
    public Page<ProcessVo> index(Long page, Long limit, ProcessQueryVo processQueryVo) {
        Page<ProcessVo> processPage = new Page<>(page,limit);
        Page<ProcessVo> pageModel = baseMapper.selectPage(processPage,processQueryVo);
        return pageModel;
    }

    /**
     * 部署流程定义
     * @param path：zip路径
     */
    @Override
    public void deployByZip(String path) {
        //定义zip输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        //流程部署
        Deployment deployment = repositoryService.createDeployment().addZipInputStream(zipInputStream).deploy();
        System.out.println(deployment.getId());
        System.out.println(deployment.getName());
    }

    /**
     * 启动流程实例
     * @param processFormVo
     */
    @Override
    public void startUp(ProcessFormVo processFormVo) {
        // 1.根据当前用户id获取用户信息
        SysUser user = userService.getById(LoginUserInfoHelper.getUserId());
        // 2. 根据审批模板id查询模板信息
        ProcessTemplate template = processTemplateService.getById(processFormVo.getProcessTemplateId());
        // 3.保存提交的审批信息到业务表，oa_process
        Process process = new Process();
        //将processFormVo复制到process
        BeanUtils.copyProperties(processFormVo,process);
        String workNo = System.currentTimeMillis() + "";
        process.setProcessCode(workNo);
        process.setUserId(LoginUserInfoHelper.getUserId());
        process.setFormValues(processFormVo.getFormValues());
        process.setTitle(user.getName() + "发起" + template.getName() + "申请");
        process.setStatus(1);//1-审批中 2-审批通过 -1-驳回 0-默认
        this.save(process);
        //4.启动流程实例 --RunTimeService
        //4.1 流程定义的key
        String processDefinitionKey = template.getProcessDefinitionKey();
        //4.2 业务key processId
        String businessKey = String.valueOf(process.getId());
        //4.3 流程参数 form表单json数据，转换成map集合
        //流程参数
        Map<String, Object> variables = new HashMap<>();
        String formValues = processFormVo.getFormValues();
        JSONObject jsonObject = JSON.parseObject(formValues);
        JSONObject formData = jsonObject.getJSONObject("formData");
        Map<String,Object> map = new HashMap<>();
        for(Map.Entry<String,Object> entry : formData.entrySet()){
            map.put(entry.getKey(),entry.getValue());
        }
        variables.put("data", map);
        //启动流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
        //5. 查询下一个审批人是谁
        List<Task> taskList = this.getCurrentTaskList(processInstance.getId());
        List<String> assigneeList = new ArrayList<>();
        for(Task task : taskList){
            SysUser sysUser = userService.getByUsername(task.getAssignee());
            assigneeList.add(sysUser.getName());//将用户的真实姓名存入list
            //TODO 6. 推送消息给下一个审批人
        }

        //7.业务和流程关联  更新oa_process
        process.setProcessInstanceId(processInstance.getId());
        process.setDescription("等待" + StringUtils.join(assigneeList.toArray(), ",") + "审批");
        this.updateById(process);
        //记录审批信息
        processRecordService.record(process.getId(),process.getStatus(),"发起申请");
    }

    @Override
    public Page<ProcessVo> findPending(Long page, Long limit) {
        //封装page对象
        Page<Process> pageParam = new Page<>(page,limit);
        //1.封装查询条件，根据当前登录的用户名称
        TaskQuery query = taskService.createTaskQuery()
                                    .taskAssignee(LoginUserInfoHelper.getUsername())
                                    .orderByTaskCreateTime()
                                    .desc();
        long totalCount = query.count();//总记录数
        //2.调用方法分页查询，返回list集合，待办任务集合
        // 第一个参数：开始位置，第二个参数：每页显示记录数
        List<Task> list = query.listPage((int) ((pageParam.getCurrent() - 1) * pageParam.getSize()), (int) pageParam.getSize());
        //3.封装返回list集合数据到list<processVo>
        List<ProcessVo> processVoList = new ArrayList<>();
        for(Task task : list){
            //从task中获得实力流程id
            String processInstanceId = task.getProcessInstanceId();
            //根据实力流程id获得实例
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //根据实例流程id获取业务key
            String businessKey = processInstance.getBusinessKey();
            if (businessKey == null){
                continue;
            }
            //根据业务key获取Process对象
            Process process = this.getById(Long.parseLong(businessKey));

            ProcessVo processVo = new ProcessVo();
            BeanUtils.copyProperties(process, processVo);
            processVo.setTaskId(task.getId());
            processVoList.add(processVo);
        }
        Page<ProcessVo> voPage = new Page<>(pageParam.getCurrent(), pageParam.getSize(), totalCount);
        voPage.setRecords(processVoList);
        return voPage;
    }

    @Override
    public Map<String, Object> show(Long id) {
        //1.根据流程id获取流程信息process
        Process process = this.getById(id);
        //2.根据流程id获取流程记录信息
        List<ProcessRecord> processRecordList = processRecordService.list(new LambdaQueryWrapper<ProcessRecord>().eq(ProcessRecord::getProcessId, id));
        //3.根据模板id获取模板信息
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());
        //4.判断用户是否可以进行审批
        //可以看到信息不一定能审批，不能重复审批
        boolean isApprove = false;
        List<Task> taskList = this.getCurrentTaskList(process.getProcessInstanceId());
        for(Task task : taskList){
            if(task.getAssignee().equals(LoginUserInfoHelper.getUsername())) {
                isApprove = true;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("process", process);
        map.put("processRecordList", processRecordList);
        map.put("processTemplate", processTemplate);
        map.put("isApprove",isApprove);
        return map;
    }

    /**
     * 进行审批
     * @param approvalVo
     */
    @Override
    public void approve(ApprovalVo approvalVo) { // 不满足并行审批流程
        //1.从approvalVo获取任务id，根据任务id获得流程变量
        String taskId = approvalVo.getTaskId();
        Map<String, Object> variables = taskService.getVariables(taskId);//获取流程变量
        for (Map.Entry<String, Object> entry : variables.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        //2.判断审批状态值

        if(approvalVo.getStatus() == 1){
            //2.1 status = 1，审批通过
            Map<String,Object> variables1 = new HashMap<>();
            taskService.complete(taskId,variables1); //审批通过，完成任务，流程自动流向下一结点
        }else{
            //2.2 status = -1 驳回，流程终止
            this.endTask(taskId);
        }

        //3 记录审批相关过程信息 oa_process_record
        String description = approvalVo.getStatus() == 1 ? "审批通过" : "审批驳回";
        processRecordService.record(approvalVo.getProcessId(),approvalVo.getStatus(),description);
        //4. 查询下一个审批人，更新流程表process记录
        Process process = this.getById(approvalVo.getProcessId());
        //查询任务
        List<Task> taskList = this.getCurrentTaskList(process.getProcessInstanceId());
        if (!CollectionUtils.isEmpty(taskList)){
            //存在下一个审批任务
            List<String> assigneeList = new ArrayList<>();
            for(Task task : taskList) {
                SysUser sysUser = userService.getByUsername(task.getAssignee());
                assigneeList.add(sysUser.getName());

                //TODO 推送消息给下一个审批人
            }
            process.setDescription("等待" + StringUtils.join(assigneeList.toArray(), ",") + "审批");
            process.setStatus(1);
        }else {
            //不存在下一个审批任务
            if(approvalVo.getStatus() == 1) { //流程完成
                process.setDescription("审批完成（同意）");
                process.setStatus(2);
            } else { //流程被动完成
                process.setDescription("审批完成（拒绝）");
                process.setStatus(-1);
            }
        }
        //TODO 消息推送给申请人
        baseMapper.updateById(process);
    }

    /**
     * 查找已处理的审批信息
     * @param pageParam
     * @return
     */
    @Override
    public IPage<ProcessVo> findProcessed(Page<Process> pageParam) {
        // 根据当前人的ID查询
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
                                                .taskAssignee(LoginUserInfoHelper
                                                .getUsername()).finished()
                                                .orderByTaskCreateTime()
                                                .desc();
        List<HistoricTaskInstance> list = query
                                        .listPage((int) ((pageParam.getCurrent() - 1) * pageParam.getSize()), (int) pageParam.getSize());
        long totalCount = query.count();//记录总数

        //遍历list，封装processVo集合
        List<ProcessVo> processList = new ArrayList<>();
        for (HistoricTaskInstance item : list) {
            String processInstanceId = item.getProcessInstanceId();
            //根据流程实例id获取process信息
            Process process = this.getOne(new LambdaQueryWrapper<Process>().eq(Process::getProcessInstanceId, processInstanceId));
            ProcessVo processVo = new ProcessVo();
            BeanUtils.copyProperties(process, processVo);
            processVo.setTaskId("0");
            processList.add(processVo);
        }
        IPage<ProcessVo> page = new Page<ProcessVo>(pageParam.getCurrent(), pageParam.getSize(), totalCount);
        page.setRecords(processList);
        return page;
    }

    /**
     * 查找发起的审批信息
     * @param pageParam
     * @return
     */
    @Override
    public IPage<ProcessVo> findStarted(Page<ProcessVo> pageParam) {
        ProcessQueryVo processQueryVo = new ProcessQueryVo();
        processQueryVo.setUserId(LoginUserInfoHelper.getUserId());
        IPage<ProcessVo> page = baseMapper.selectPage(pageParam, processQueryVo);
        for (ProcessVo item : page.getRecords()) {
            item.setTaskId("0");
        }
        return page;
    }

    /**
     * 终止流程
     * @param taskId
     */
    private void endTask(String taskId) {
        //1. 根据任务id获取任务对象
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //2.获取流程定义模型BpmnModel
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        //3.获取结束流向节点
        List endEventList = bpmnModel.getMainProcess().findFlowElementsOfType(EndEvent.class);
        // 并行任务可能为null
        if(CollectionUtils.isEmpty(endEventList)) {
            return;
        }
        FlowNode endFlowNode = (FlowNode) endEventList.get(0);
        //4.获取当前流向节点
        FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());
        //  临时保存当前活动的原始方向
        List originalSequenceFlowList = new ArrayList<>();
        originalSequenceFlowList.addAll(currentFlowNode.getOutgoingFlows());
        //5.清理当前流向方向
        currentFlowNode.getOutgoingFlows().clear();
        //6.创建新的流向
        SequenceFlow newSequenceFlow = new SequenceFlow();
        newSequenceFlow.setId("newSequenceFlowId");
        newSequenceFlow.setSourceFlowElement(currentFlowNode);
        newSequenceFlow.setTargetFlowElement(endFlowNode);
        List newSequenceFlowList = new ArrayList<>();
        newSequenceFlowList.add(newSequenceFlow);
        //7.当前节点指向新流向
        currentFlowNode.setOutgoingFlows(newSequenceFlowList);
        //8.完成当前任务
        taskService.complete(task.getId());
    }

    /**
     * 获取当前任务列表
     * @param id
     * @return
     */
    private List<Task> getCurrentTaskList(String id) {
        List<Task> taskList = taskService.createTaskQuery().processInstanceId(id).list();
        return taskList;

    }
}
